package com.lookme.lmtool.utils;

import com.jfoenix.controls.JFXAlert;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialogLayout;
import com.jfoenix.svg.SVGGlyph;
import com.lookme.core.javafx.FxApp;
import com.lookme.lmtool.model.Env;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.awt.*;
import java.io.File;
import java.util.concurrent.CountDownLatch;

public class ToolUtils {
    public static ImageView getButtonGraphics(String res){
        ImageView imageView = new ImageView(res);
        imageView.setFitWidth(16);
        imageView.setFitHeight(16);
        return imageView;
    }

    public static ImageView getButtonGraphics(String res,int fillWidth,int fillHeight){
        ImageView imageView = new ImageView(res);
        imageView.setFitWidth(fillWidth);
        imageView.setFitHeight(fillHeight);
        return imageView;
    }

    public static Image getImage(String res){
        Image image=new Image(res);
        return image;
    }
    public static SVGGlyph createSVGGlyph(String glyph){
        return createSVGGlyph(glyph, 24, 24, Color.WHITE);
    }

    public static SVGGlyph createSVGGlyph(String glyph, int width, int height, Color color){
        SVGGlyph svgGlyph = new SVGGlyph(0, "", glyph, color);
        svgGlyph.setSize(width,height);
        return svgGlyph;
    }



    public static FileChooser createFileChooser(String title){
        FileChooser fileChooser = new FileChooser();
        if (Env.getInstance().getInitDirectory() != null) {
            fileChooser.setInitialDirectory(new File(Env.getInstance().getInitDirectory()));
        }
        FileChooser.ExtensionFilter extFilterCrp = new FileChooser.ExtensionFilter("识别工程(.crp)", "*.crp");
        fileChooser.getExtensionFilters().addAll(extFilterCrp);
        fileChooser.setTitle(title);
        return fileChooser;
    }

    public static File chooseFile(File initDirectory,FileChooser.ExtensionFilter... extensionFilter) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("请选择文件");
        fileChooser.setInitialDirectory(initDirectory);

        if (extensionFilter != null) {
            fileChooser.getExtensionFilters().addAll(extensionFilter);
        }

        return fileChooser.showOpenDialog(null);
    }


    public static WritableImage snapshot(Node node) {
        //以下两句是设置截图的参数，具体细节还没有研究
        final javafx.scene.SnapshotParameters params
                = new javafx.scene.SnapshotParameters();
        params.setFill(Color.TRANSPARENT);
        //对Node进行截图，只会截取显示出来的部分，未显示出来的部分无法截图（没有火狐截图高级）
        WritableImage snapshot = node.snapshot(params, null);
//        //将JavaFX格式的WritableImage对象转换成AWT BufferedImage 对象来进行保存
//        final java.awt.image.BufferedImage image
//                = javafx.embed.swing.SwingFXUtils.fromFXImage(snapshot, null);
        return snapshot;
    }

    /**
     *
     * @param control
     * @return
     */
    public static double getScreenX(Control control){
        return control.getScene().getWindow().getX()+control.getScene().getX()+ control.localToScene(0, 0).getX();
    }
    public static double getScreenY(Control control){
        return control.getScene().getWindow().getY()+control.getScene().getY()+ control.localToScene(0, 0).getY();
    }
    public static double getWidth(Control control){
        return control.getBoundsInParent().getWidth();
    }
    public static double getHeight(Control control){
        return control.getBoundsInParent().getHeight();
    }


    public static void showAlert(Stage stage,String content) {
        showAlert(stage,"提示内容",content,"确定");
    }
    public static void showAlert(Stage stage,String title,String content) {
        showAlert(stage,title,content,"确定");
    }

    public static void showAlert(Stage stage,String title,String content,String buttonText) {
        JFXAlert alert = new JFXAlert(stage);
        alert.initModality(Modality.APPLICATION_MODAL);
        alert.setOverlayClose(false);
        JFXDialogLayout layout = new JFXDialogLayout();
        layout.setHeading(new Label(title));
        layout.setBody(new Label(content));
        JFXButton closeButton = new JFXButton(buttonText);
        closeButton.getStyleClass().add("dialog-accept");
        closeButton.setOnAction(event -> alert.hideWithAnimation());
        layout.setActions(closeButton);
        alert.setContent(layout);
        alert.show();
    }
    /**
     * 获取到classes目录
     * @return path
     */
    public static String getClassPath(){
        String systemName = System.getProperty("os.name");//windows 10
        //判断当前环境，如果是Windows 要截取路径的第一个 '/'
        //indexOf 方法返回一个整数值，指出 String 对象内子字符串的开始位置。如果没有找到子字符串，则返回-1

        String path=getPath();
        if(path!=null){
            return path;
        }
        if(!StringUtils.isBlank(systemName) && systemName.indexOf("Windows") !=-1){
            return ToolUtils.class.getResource("/").getFile().toString().substring(1);
        }else{
            return ToolUtils.class.getResource("/").getFile().toString();
        }
    }
    public static String getPath()
    {
        String path = ToolUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        if(System.getProperty("os.name").contains("dows"))
        {
            path = path.substring(1,path.length());
        }
        if(path.contains("jar"))
        {
            path = path.substring(0,path.lastIndexOf("."));
            return path.substring(0,path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "")+"/";
    }


    public static void initWebViewZoom(WebView webView){
        try {
            int width = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
            int height = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
            if(height<1000){
                webView.setZoom(0.8);
            }else if(height<=1080){
                webView.setZoom(0.9);
            }
        }catch(Exception e){

        }
        webView.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.isControlDown() && event.getCode() == KeyCode.DOWN) {
                    webView.setZoom(webView.getZoom() - 0.05);
                } else {
                    if (event.isControlDown() && event.getCode() == KeyCode.UP) {
                        webView.setZoom(webView.getZoom() + 0.05);
                    }
                }
            }
        });
    }


    public static void runAndWait(Runnable action) {
        if (action == null) {
            throw new NullPointerException("action");
        }

        // run synchronously on JavaFX thread
        if (Platform.isFxApplicationThread()) {
            action.run();
            return;
        }

        // queue on JavaFX thread and wait for completion
        final CountDownLatch doneLatch = new CountDownLatch(1);
        Platform.runLater(() -> {
            try {
                action.run();
            } finally {
                doneLatch.countDown();
            }
        });

        try {
            doneLatch.await();
        } catch (InterruptedException e) {
            // ignore exception
        }
    }

}
